package cn.djb.day12;

import cn.djb.day2.ListNode;

class Solution {

    /**
     * 正常递归
     *
     * @param l1
     * @param l2
     * @return
     */
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (null == l1 && null == l2) {
            return null;
        }
        if (null == l1) {
            return l2;
        }
        if (null == l2) {
            return l1;
        }
        ListNode node;
        if (l1.val > l2.val) {
            node = new ListNode(l2.val);
            node.next = mergeTwoLists(l1, l2.next);
        } else {
            node = new ListNode(l1.val);
            node.next = mergeTwoLists(l1.next, l2);
        }
        return node;

    }

    /**
     * 使用头结点
     *
     * @param l1
     * @param l2
     * @return
     */
    public ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);

        ListNode temp = head;
        while (l1 != null && l2 != null) {
            if (l1.val>l2.val){
                temp.next = l2;
                ListNode tmp = l2.next;
                l2.next = null;
                l2 = tmp;
            }else {
                temp.next = l1;
                ListNode tmp = l1.next;
                l1.next = null;
                l1 = tmp;
            }
            temp = temp.next;
        }
        temp.next = l1 != null ? l1 : l2;

        return head.next;

    }


}